package com.sanjiahantang.youjiarole.module.me.order.views.impl;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.sanjiahantang.uilibrary.adapter.listview.BaseAdapterHelper;
import com.sanjiahantang.uilibrary.adapter.listview.QuickAdapter;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiarole.R;
import com.sanjiahantang.youjiarole.base.BaseMvpFragment;
import com.sanjiahantang.youjiarole.base.BaseView;
import com.sanjiahantang.youjiarole.config.ConfigValue;
import com.sanjiahantang.youjiarole.config.SPConfig;
import com.sanjiahantang.youjiarole.module.city.views.impl.CityActivity;
import com.sanjiahantang.youjiarole.module.decorate.views.impl.DecorateDetailActivity;
import com.sanjiahantang.youjiarole.module.join.beans.CertificationResponseBean;
import com.sanjiahantang.youjiarole.module.me.order.beans.OrderTakeNumberResponseBean;
import com.sanjiahantang.youjiarole.module.me.order.beans.OrderTakeResponseBean;
import com.sanjiahantang.youjiarole.module.me.order.presenters.OrderPresenter;
import com.sanjiahantang.youjiarole.module.me.order.views.OrderView;
import com.sanjiahantang.youjiarole.module.me.require.views.impl.RequireDetailActivity;
import com.sanjiahantang.youjiarole.utils.CheckUtil;
import com.sanjiahantang.youjiarole.utils.SPUtils;

import java.util.List;

import q.rorbin.badgeview.QBadgeView;

/**
 * Created by zy on 2017/10/29.
 */

public class OrderTakeFragment extends BaseMvpFragment<OrderView, OrderPresenter> implements OrderView, View.OnClickListener, BaseView.OnLoadListener {

    private View mView, unDot, dot,vsNetworkError;
    private QuickAdapter<OrderTakeResponseBean.Data> otAdapter;
    private ListView listView;
    private boolean flag;//是否接单
    private String role;
    private TextView txtUnTokenOrder, txtTokenOrder, title;
    private QBadgeView qBadgeView1, qBadgeView2;
    private SwipeRefreshLayout refreshLayout;
    private String currentPhone;

    @Override
    public void showProgress() {
        if (context != null) refreshLayout.setRefreshing(true);
    }

    @Override
    public void hideProgress() {
        if (context != null) refreshLayout.setRefreshing(false);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_order_take, container, false);
        return mView;
    }

    @Override
    public OrderPresenter initPresenter() {
        return new OrderPresenter();
    }

    @Override
    protected void initView() {
        mView.findViewById(R.id.back).setVisibility(View.GONE);
        title = (TextView) mView.findViewById(R.id.title);
        title.setFilters(new InputFilter[] { new InputFilter.LengthFilter(4) });
        title.setEllipsize(TextUtils.TruncateAt.MARQUEE);

        mView.findViewById(R.id.ivArcher).setVisibility(View.VISIBLE);
        mView.findViewById(R.id.panelTitle).setOnClickListener(this);

        qBadgeView1 = new QBadgeView(context);
        qBadgeView2 = new QBadgeView(context);
        unDot = mView.findViewById(R.id.unDot);
        vsNetworkError = mView.findViewById(R.id.vsNetworkError);
        refreshLayout = (SwipeRefreshLayout) mView.findViewById(R.id.refreshLayout);
        dot = mView.findViewById(R.id.dot);
        mView.findViewById(R.id.vWaitToTakeOrder).setOnClickListener(this);
        mView.findViewById(R.id.vTokenOrder).setOnClickListener(this);

        listView = (ListView) mView.findViewById(R.id.listView);
        currentPhone = SPUtils.get(context,SPConfig.PHONE,"").toString();
        otAdapter = new QuickAdapter<OrderTakeResponseBean.Data>(context, R.layout.item_order_take) {
            @Override
            protected void convert(BaseAdapterHelper helper, final OrderTakeResponseBean.Data item) {
                //恢复初始化
                helper.setText(R.id.txtApartName, item.getApartmentName());
                helper.setVisible(R.id.txtMessage, false);
                helper.getView().setOnClickListener(null);
                ImageView ivPhone = helper.getView(R.id.ivPhone);
                ivPhone.setImageResource(R.drawable.i_phone_green_strike);
                helper.setOnClickListener(R.id.vPhone, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent1 = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + item.getPhone()));
                        intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent1);
                    }
                });


                helper.setText(R.id.txtCity, item.getAddress());
                helper.setText(R.id.txtState, item.getStateName());
                helper.setText(R.id.txtName, item.getUserName());
                helper.setVisible(R.id.txtSubPackage,false);
                if (flag) {
                    helper.setVisible(R.id.txtState, false);
                    if (item.getStateName() != null && item.getStateName().contains("监理")) {
                        helper.setVisible(R.id.btnAction, false);
                    } else if (item.getStateName() != null && item.getStateName().contains("项目经理")) {

                        //工程分包项目
                        if ("1".equals(item.getIsSubcontract())){
                            helper.setVisible(R.id.txtSubPackage,true);
                            if (currentPhone.equals(item.getSubcontractPhone())){
                                helper.setText(R.id.txtSubPackage,"来自: " + item.getSubcontractRoleName() + "(" + item.getSubcontractRoleId() + ")");
                            }else if (currentPhone.equals(item.getSubcontractRoleId())){
                                helper.setText(R.id.txtSubPackage,"分包: " + item.getSubcontractName() + "(" + item.getSubcontractPhone() + ")");
                            }
                        }

                        if (item.getProjectRecommend() == 1 && "1".equals(item.getIsSubcontract())) {
                            helper.setVisible(R.id.btnAction, true);
                            helper.setText(R.id.btnAction, "进入工程");
                        } else if (item.getStateName() != null && item.getProjectRecommend() == 0) {
                            helper.setVisible(R.id.btnAction, true);
                            helper.setText(R.id.btnAction, "推荐合伙人");
                        }else{
                            helper.setVisible(R.id.btnAction, false);
                        }
                    } else if (item.getStateName() != null && item.getStateName().contains("设计师")) {
                        helper.getView().setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(context, RequireDetailActivity.class);
                                intent.putExtra(KEY_ID, item.getId());
                                intent.putExtra("state", 1);
                                intent.putExtra("type", 0);
                                startActivity(intent);
                            }
                        });
                        //设计分包项目
                        if ("1".equals(item.getIsSubcontract())){
                            helper.setVisible(R.id.txtSubPackage,true);
                            if (currentPhone.equals(item.getSubcontractPhone())){
                                helper.setText(R.id.txtSubPackage,"来自: " + item.getSubcontractRoleName() + "(" + item.getSubcontractRoleId() + ")");
                            }else if (currentPhone.equals(item.getSubcontractRoleId())){
                                helper.setText(R.id.txtSubPackage,"分包: " + item.getSubcontractName() + "(" + item.getSubcontractPhone() + ")");
                            }
                        }

                        if ("1".equals(item.getIsDesignFree())) {
                            helper.setVisible(R.id.btnAction, false);
                            helper.setVisible(R.id.txtMessage, true);
                            helper.setText(R.id.txtMessage, "此设计免费");
                        } else {
                            if ("1".equals(item.getIsCommitOrder())) {
                                helper.setVisible(R.id.btnAction, false);
                                helper.setVisible(R.id.txtMessage, true);
                                if (item.getContractPrice() != null) {
                                    helper.setText(R.id.txtMessage, "合同金额:　" + item.getContractPrice());
                                } else {
                                    helper.setVisible(R.id.txtMessage, false);
                                }

                            } else {
                                helper.setVisible(R.id.btnAction, true);
                                helper.setText(R.id.btnAction, "设计报价");
                            }
                        }
                    } else {
                        helper.setVisible(R.id.btnAction, false);
                    }
                } else {
                    helper.setVisible(R.id.txtState, true);
                    helper.setText(R.id.btnAction, "接单");
                    helper.setVisible(R.id.btnAction, true);

                    if (item.getIsBidProject() == 1 && (item.getStateName() != null && item.getStateName().contains("设计师"))) {
                        helper.setText(R.id.btnAction, "投标");

                        ivPhone.setImageResource(R.drawable.i_phone_gray_strike);
                        helper.setOnClickListener(R.id.vPhone, null);
                    }
                }

                helper.setOnClickListener(R.id.btnAction, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        String role = SPUtils.get(context, SPConfig.ROLE_ID, "").toString();
                        //待接单列表事件
                        if (!flag) {
                            if (item.getIsBidProject() == 1 && (item.getStateName() != null && item.getStateName().contains("设计师"))) {
                                presenter.findBidRequireInfoForRole(context, item.getId(), new BaseView.OnLoadListener() {
                                    @Override
                                    public void onLoad(Object content) {
                                        Intent intent = new Intent(context, RequireDetailActivity.class);
                                        intent.putExtra(KEY_ID, item.getId());
                                        intent.putExtra("state", 3);
                                        intent.putExtra("type", 0);
                                        startActivity(intent);
                                    }
                                });

                            } else {
                                int type = -1;
                                if (item.getStateName().contains("设计师")) {
                                    type = 0;
                                } else if (item.getStateName().contains("项目经理")) {
                                    type = 1;
                                } else if (item.getStateName().contains("监理")) {
                                    type = 2;
                                }

                                if (role.contains(String.valueOf(type))) {
                                    Intent intent = new Intent(context, RequireDetailActivity.class);
                                    intent.putExtra(KEY_ID, item.getId());
                                    intent.putExtra("state", flag ? 1 : 2);
                                    intent.putExtra("type", type);
                                    startActivity(intent);
                                }
                            }

                        } else {
                            int type = -1;
                            if (item.getStateName().contains("设计师")) {
                                type = 0;
                            } else if (item.getStateName().contains("项目经理")) {
                                type = 1;
                            } else if (item.getStateName().contains("监理")) {
                                type = 2;
                            }

                            if (role.contains(String.valueOf(type))) {
                                if (type == 1 && item.getProjectRecommend() > 0){
                                    Intent intent = new Intent(context,DecorateDetailActivity.class);
                                    intent.putExtra(KEY_ID,String.valueOf(item.getId()));
                                    startActivity(intent);
                                } else {
                                    Intent intent = new Intent(context, RequireDetailActivity.class);
                                    intent.putExtra(KEY_ID, item.getId());
                                    intent.putExtra("state", flag ? 1 : 2);
                                    intent.putExtra("type", type);
                                    startActivity(intent);
                                }

                            }
                        }


                    }
                });
            }
        };

        listView.setAdapter(otAdapter);

        txtUnTokenOrder = (TextView) mView.findViewById(R.id.txtUnTokenOrder);
        txtTokenOrder = (TextView) mView.findViewById(R.id.txtTokenOrder);


        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshList(!flag);
            }
        });

        loadRole(null);
    }

    private void loadRole(final BaseView.OnLoadListener listener){

        title.setText("接单");
        mView.findViewById(R.id.ivArcher).setVisibility(View.GONE);
        mView.findViewById(R.id.panelTitle).setOnClickListener(null);
        CheckUtil.isRoleValid(context,true, new BaseView.OnLoadListener() {
            @Override
            public void onLoad(Object content) {
                role = SPUtils.get(context, SPConfig.ROLE_ID, "").toString();
                hideProgress();
                if (TextUtils.isEmpty(role) || !(role.contains("0") || role.contains("1"))) {
                    title.setText("接单");
                    mView.findViewById(R.id.ivArcher).setVisibility(View.GONE);
                    mView.findViewById(R.id.panelTitle).setOnClickListener(null);
                }else{
                    mView.findViewById(R.id.ivArcher).setVisibility(View.VISIBLE);
                    mView.findViewById(R.id.panelTitle).setOnClickListener(OrderTakeFragment.this);
                    if (!TextUtils.isEmpty(ConfigValue.city)) {
                        title.setText(ConfigValue.city);
                    } else {
                        title.setText("全国");
                    }
                }
                if (listener != null){
                    listener.onLoad(null);
                }
            }
        });
    }

    private void refreshList(final boolean action) {
        if (Utils.NO_NETWORK_STATE == Utils.isNetworkAvailable(context)) {
            onNetError(true);
            return;
        }else{
            onNetError(false);
        }
        loadRole(new BaseView.OnLoadListener() {
            @Override
            public void onLoad(Object content) {
                if (action) {
                    txtUnTokenOrder.setTextColor(COLOR_PRIMARY);
                    txtUnTokenOrder.setBackgroundResource(R.drawable.x_line_green);
                    txtTokenOrder.setTextColor(getResources().getColor(R.color.black_60));
                    txtTokenOrder.setBackgroundColor(Color.TRANSPARENT);
                } else {
                    txtTokenOrder.setTextColor(COLOR_PRIMARY);
                    txtTokenOrder.setBackgroundResource(R.drawable.x_line_green);
                    txtUnTokenOrder.setTextColor(getResources().getColor(R.color.black_60));
                    txtUnTokenOrder.setBackgroundColor(Color.TRANSPARENT);
                }
                presenter.initSearchRequire(context, new BaseView.OnLoadListener() {
                    @Override
                    public void onLoad(Object content) {
                        refreshLayout.setRefreshing(false);
                        if (content instanceof OrderTakeNumberResponseBean.Data) {
                            OrderTakeNumberResponseBean.Data bean = (OrderTakeNumberResponseBean.Data) content;
                            if (bean.getNocount() != null && bean.getNocount().getResult() > 0) {
                                qBadgeView1.bindTarget(unDot).setBadgeGravity(Gravity.TOP | Gravity.END)
                                        .setBadgeNumber(bean.getNocount().getResult())
                                        .setGravityOffset(0, 2, true)
                                        .setBadgeBackgroundColor(COLOR_PRIMARY)
                                        .setBadgeTextSize(8, true);
                                qBadgeView1.setVisibility(View.VISIBLE);
                            } else {
                                qBadgeView1.setVisibility(View.GONE);
                            }

                            if (bean.getCount() != null && bean.getCount().getResult() > 0) {
                                qBadgeView2.bindTarget(dot).setBadgeGravity(Gravity.TOP | Gravity.END)
                                        .setBadgeNumber(bean.getCount().getResult())
                                        .setGravityOffset(0, 2, true)
                                        .setBadgeBackgroundColor(COLOR_PRIMARY)
                                        .setBadgeTextSize(8, true);
                                qBadgeView2.setVisibility(View.VISIBLE);
                            } else {
                                qBadgeView2.setVisibility(View.GONE);
                            }

                            checkRadioButton(action);
                        }

                    }
                });
            }
        });
    }

    public void onNetError(boolean b) {
        if (b){
            vsNetworkError.setVisibility(View.VISIBLE);
            vsNetworkError.findViewById(R.id.btnReloadNetwork).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onResume();
                }
            });
        }else{
            vsNetworkError.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.vWaitToTakeOrder:
                refreshList(true);
                break;
            case R.id.vTokenOrder:
                refreshList(false);
                break;
            case R.id.panelTitle:
                startActivityForResult(new Intent(context, CityActivity.class), INTENT_CITY);
                break;
        }
    }

    private void checkRadioButton(boolean b) {
        flag = !b;
        presenter.loadOrderTakeList(context, flag, this);
    }

    @Override
    public void onLoad(Object content) {
        List<OrderTakeResponseBean.Data> list = (List<OrderTakeResponseBean.Data>) content;
        otAdapter.clear();
        otAdapter.addAll(list);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(role)) {
            refreshList(!flag);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == INTENT_CITY && resultCode == Activity.RESULT_OK) {
            if (ConfigValue.city == null){
                title.setText("全国");
            }else{
                title.setText(ConfigValue.city);
            }
        }
    }
}
